package com.lhl.servlet;

import com.lhl.dao.StudentDao;
import com.lhl.dao.StudentDaoImpl;
import com.lhl.entity.Student;
import com.lhl.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/queryStudentById")
public class QueryStudentByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String id1 = request.getParameter("id");
        System.out.println(id1);
        List<Student> students = new ArrayList<>();
        StudentDao dao = new StudentDaoImpl();
        int id = 0;
        if (id1.equals("")) {
            students = dao.queryAllStudents();
        } else {
            try {
                id = Integer.parseInt(id1);
                Student student = dao.queryStudent(id);
                if (student.getId() == 0)
                    students = dao.queryAllStudents();
                else
                    students.add(student);
            } catch (Exception e) {
                students = dao.queryAllStudents();
            }
        }
        response.getWriter().print(JsonUtils.getJson(students));
    }
}
